<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\Bankuai;
use app\admin\model\Equipment;
use fast\Http;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }
	
	public function getAccessToken()
	{
		$accessToken = getAccessToken();
		
		$this->success('success', $accessToken);
	}
	
	public function getBankuai()
	{
		$bankuai = Bankuai::Field('id, bk_name,shebei')->whereIn('id', $this->auth->bankuai)->select();
		foreach($bankuai as &$vo)
		{
			$vo['shebei'] = Equipment::Field('id, device_name,device_serial')->whereIn('id', $vo->shebei)->select();
		}
		
		$this->success('success', $bankuai);
	}
	
	public function addBankuai()
	{
		$content = trim($this->request->post("content"));
		
		$data = array('bk_name'=>$content);
		$bankuai = Bankuai::create($data);
		
		$user = $this->auth->getUser();
		$user->bankuai = $user->bankuai.','.$bankuai->id;
		$user->save();
		
		$this->success('success');
	}
	
	public function getBkList()
	{
		$bankuai = Bankuai::Field('id, bk_name as text')->whereIn('id', $this->auth->bankuai)->select();
		$this->success('success', $bankuai);
	}
	
	public function addShebei()
	{
		$bk_id = intval($this->request->post("bk_id"));
		$device_name = trim($this->request->post("device_name"));
		$device_serial = trim($this->request->post("device_serial"));
		$validate_code = trim($this->request->post("validate_code"));
		
		$accessToken = getAccessToken();
		$result = Http::post('https://open.ys7.com/api/lapp/device/add', array('accessToken'=>$accessToken, 'deviceSerial'=>$device_serial, 'validateCode'=>$validate_code));
		$result = json_decode($result, true);
		if($result['code'] == 200)
		{
			$data = array('bk_id'=>$bk_id, 'device_serial'=>$device_serial, 'device_name'=>$device_name);
			$shebei = Equipment::create($data);
			
			$bk = Bankuai::get($bk_id);
			$bk->shebei = $bk->shebei.','.$shebei->id;
			$bk->save();
		}
		else
		{
			$this->error($result['msg']);
		}
		
		
		$this->success('success');
	}
}
